package com.zhuoli.service.springboot.redis.repository.config;

import com.zhuoli.service.redis.client.template.redis.RedisTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @Author: zhuoli
 * @Date: 2018/8/26 10:45
 * @Description:
 */
@Configuration
@Slf4j
public class RedisConfig {

    @Value("${zhuoli.redis.url}")
    private String redisUri;

    @Value("${zhuoli.redis.timeout}")
    private Integer timeOut;

    @Value("${zhuoli.redis.size}")
    private Integer size;

    @Bean
    public RedisTemplate redisTemplate(){
        JedisPool jedisPool = null;
        try {
            jedisPool = new JedisPool(jedisPoolConfig(size), new URI(redisUri), timeOut);
        } catch (URISyntaxException e) {
            log.info("Jedis Pool Init Exception, message is {}", e);
        }
        return new RedisTemplate(jedisPool);
    }

    private JedisPoolConfig jedisPoolConfig(int size) {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMinIdle(size);
        jedisPoolConfig.setMaxIdle(2 * size);
        jedisPoolConfig.setMaxTotal(2 * size);
        jedisPoolConfig.setMaxWaitMillis(3000L);
        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestOnReturn(true);
        jedisPoolConfig.setTestWhileIdle(true);
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(1000);
        return jedisPoolConfig;
    }
}
